package oo

import (
	"bytes"
	"encoding/csv"
	"io/ioutil"
	"strings"
)

// CSVRead
func CSVRead(reader *csv.Reader) (rows []map[string]string, err error) {
	head, err := reader.Read()
	if err != nil {
		return
	}

	lines, err := reader.ReadAll()
	if err != nil {
		return
	}

	rows = make([]map[string]string, len(lines))
	for i, line := range lines {
		row := make(map[string]string, len(line))
		for j := range line {
			row[head[j]] = line[j]
		}
		rows[i] = row
	}
	return
}

// CSVReadFromString
func CSVReadFromString(s string) (rows []map[string]string, err error) {
	return CSVRead(csv.NewReader(strings.NewReader(s)))
}

// CSVReadFromFile
func CSVReadFromFile(filename string) (rows []map[string]string, err error) {
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return
	}

	return CSVRead(csv.NewReader(bytes.NewReader(data)))
}
